<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
        <el-form-item label="分析单号" prop="kaCode">
          <el-input
            v-model="queryParams.kaCode"
            placeholder="请输入分析单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="分析名称" prop="kaName">
          <el-input
            v-model="queryParams.kaName"
            placeholder="请输入分析名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="分析日期" prop="kaDate">
          <el-date-picker clearable
                          v-model="queryParams.kaDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择分析日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划编码" prop="planCode">
          <el-input
            v-model="queryParams.planCode"
            placeholder="请输入计划编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品编码" prop="productCode">
          <el-input
            v-model="queryParams.productCode"
            placeholder="请输入产品编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['mes:pro:analysis:add']"
          >新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="analysisList" @selection-change="handleSelectionChange">
        <el-table-column label="分析单号" align="center" prop="kaCode"/>
        <el-table-column label="分析名称" align="center" prop="kaName"/>
        <el-table-column label="计划编码" align="center" prop="planCode"/>
        <el-table-column label="产品编码" align="center" prop="productCode"/>
        <el-table-column label="产品名称" align="center" prop="productName"/>
        <el-table-column label="分析日期" align="center" prop="kaDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.kaDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.status == 0">未分析</el-tag>
            <el-tag type="warning" v-else-if="scope.row.status == -1">部分齐套</el-tag>
            <el-tag type="success" v-else-if="scope.row.status == 1">已齐套</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mes:pro:analysis:edit']"
            >分析
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mes:pro:analysis:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="optType == 'view'">
        <el-row>
          <el-col :span="9">
            <el-form-item label="分析单号" prop="kaCode">
              <el-input v-model="form.kaCode" placeholder="请输入分析单号" :readonly="optType !='add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="分析名称" prop="kaName">
              <el-input v-model="form.kaName" placeholder="请输入分析名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划编号" prop="planCode">
              <el-input v-model="form.planCode" placeholder="请输入计划编号">
                <el-button slot="append" icon="el-icon-search" @click="handlePlanSelect"></el-button>
              </el-input>
            </el-form-item>
            <PlanningSelect ref="planSelect" @onSelected="onPlanSelected" :status="planStatus"></PlanningSelect>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="9">
            <el-form-item label="产品编号">
              <el-input v-model="form.productCode" disabled placeholder="请选择产品"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="产品名称">
              <el-input v-model="form.productName" disabled placeholder="请选择产品"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划数量" prop="planQuantity">
              <el-input-number v-model="form.planQuantity" disabled placeholder="请输入计划数量"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="9">
            <el-form-item label="BOM编号">
              <el-input v-model="form.bomCode" disabled placeholder="请选择BOM编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="选择仓库" prop="warehouseId">
              <el-cascader v-model="warehouseInfo"
                           :options="warehouseOptions"
                           :props="warehouseProps"
                           style="width: 100%;"
                           @change="handleWarehouseChanged"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-card class="box-card" v-if="form.id != null">
        <AnalysisBom @refresh-list="getList" ref="matlist" :kaLockedKits="form.lockedKits" :planQuantity="form.planQuantity" :planIds="[form.planId]" :kaId="form.id"
                     :optType="optType"></AnalysisBom>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType != 'view'">确 认</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addAnalysis, delAnalysis, getAnalysis, listAnalysis, updateAnalysis } from "@/api/mes/pro/analysis";
import { genCode } from "@/api/system/autocode/rule";
import { getTreeList } from "@/api/mes/wm/warehouse";
import PlanningSelect from "@/components/planSelect/single.vue";
import { getRouteproduct } from "@/api/mes/pro/routeproduct";
import AnalysisBom from "./bom/bom.vue";

export default {
  name: "Analysis",
  components: {PlanningSelect, AnalysisBom},
  data() {
    return {
      warehouseCode: 'XBK_VIRTUAL', //线边库
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: true,
        value: 'pId',
        label: 'pName',
      },
      //自动生成编号
      autoGenFlag: false,
      planStatus: 'DAIFENJIE',
      // 遮罩层
      loading: true,
      optType: undefined,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 齐套分析表格数据
      analysisList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        kaCode: null, kaName: null, kaDate: null, planCode: null, planName: null, productCode: null, productName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        kaCode: [
          {required: true, message: "分析单号不能为空", trigger: "blur"}
        ], planCode: [
          {required: true, message: "计划编码不能为空", trigger: "blur"}
        ], planQuantity: [
          {required: true, message: "计划数量不能为空", trigger: "blur"}
        ], warehouseId: [
          {required: true, message: "仓库不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
  },
  methods: {
    /** 查询齐套分析列表 */
    getList() {
      this.loading = true;
      listAnalysis(this.queryParams).then(response => {
        this.analysisList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        kaCode: null,
        kaName: null,
        kaDate: null,
        planId: null,
        planCode: null,
        planName: null,
        planQuantity: null,
        productId: null,
        productCode: null,
        productName: null,
        lockedKits: null,
        warehouseId: null,
        locationId: null,
        areaId: null,
        status: "0",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        bomId: null,
        bomCode: null,
      };
      this.autoGenFlag = false;
      this.warehouseInfo = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.optType = "add";
      this.title = "添加齐套分析";
      this.handleAutoGenChange(true);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAnalysis(id).then(response => {
        this.form = response.data;
        this.warehouseInfo = JSON.parse(response.data.warehouseId);
        this.open = true;
        this.optType = "view";
        this.title = "齐套分析";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.warehouseId = JSON.stringify(this.warehouseInfo);
          if (this.form.id != null) {
            updateAnalysis(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAnalysis(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除齐套分析编号为"' + row.kaCode + '"的数据项？').then(function () {
        return delAnalysis(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pro/analysis/export', {
        ...this.queryParams
      }, `analysis_${new Date().getTime()}.xlsx`)
    },

    //自动生成编号
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('AOM_CODE').then(response => {
          this.form.kaCode = response;
        });
      } else {
        this.form.kaCode = null;
      }
    },
    //选择生产工单
    handlePlanSelect() {
      this.$refs.planSelect.showFlag = true;
    },
    onPlanSelected(row) {
      if (row != undefined && row != null) {
        this.form.planName = row.planName;
        this.form.planCode = row.planCode;
        this.form.planId = row.planId;
        this.form.planQuantity = row.quantity;
        this.form.productId = row.productId;
        this.form.productCode = row.productCode;
        this.form.productName = row.productName;
        if (row.attr1) {
          getRouteproduct(row.attr1).then(response => {
            this.form.bomId = response.data.bomId;
            this.form.bomCode = response.data.bomCode;
          })
        } else {
          this.form.bomId = null;
          this.form.bomCode = null;
        }
      }
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj) {
      if (obj != null) {
        this.form.warehouseId = obj
      }
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
  }
};
</script>
